//     $Id: MainWindow.java,v 1.11 2009-04-18 13:48:40 mbickel Exp $
//
//     $Log: not supported by cvs2svn $
//     Revision 1.10  2000/11/08 19:50:25  mbickel
//      Fixed Nullpointer exception when the last directory doesn't exist any
//       more on startup.
//
//     Revision 1.9  2000/11/07 16:19:39  schelli
//     Minor Memory-Functions & Problems changed
//     Picture Support partly enabled
//     New Funktion partly implemented
//     Buildings partly implemented
//
//     Revision 1.8  2000/11/01 11:41:04  mbickel
//      Fixed: Selection in MainWindow-List not being evaluated, the first list
//       entry was always edited.
//
//     Revision 1.7  2000/10/31 18:06:46  mbickel
//      Fileselector now displays files too
//
//     Revision 1.6  2000/10/29 21:06:03  mbickel
//      Modified filename construction to run under Linux
//      Started implementing a better directory choosing dialog
//
//     Revision 1.5  2000/10/24 15:35:13  schelli
//     MapEd FullScreen support added
//     weapons ammo now editable in MapEd
//
//     Revision 1.4  2000/10/17 20:21:03  schelli
//     App now remembers path
//
//     Revision 1.3  2000/10/17 17:28:26  schelli
//     minor bugs fixed in lots of sources
//     add & remove weapon works now
//     revert to save button removed
//     class-handling bugs fixed
//     load & save routines fully implemented
//     terrainacces added
//
//     Revision 1.2  2000/10/13 13:15:46  schelli
//     Load&Save routines finished
//

/*
 * MainWindow.java
 *
 * Created on 7. November 1999, 01:36

This file is part of Advanced Strategic Command; http://www.asc-hq.de
Copyright (C) 1994-2000  Martin Bickel  and  Marc Schellenberger

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA  02111-1307  USA
 */


public class MainWindow extends javax.swing.JFrame {

    int selection = 0;
    int initDone;
    public javax.swing.JList fileList;
    ErrorMessage errMsg;
    SgStream input;
    SgStream output;

    String CfgFile = "MainWindow.cfg";
    String paths[];
    String files[];

    /** Creates new form JFrame */
    public MainWindow() {
        initComponents ();

        initDone = 0;

        setTitle("ASC File Editor");

        for(int i= 0; i < descriptions.length;i++)
        jComboBoxType.addItem(descriptions[i]);

        paths = new String[descriptions.length];
        for(int i= 0; i < descriptions.length;i++) paths[i] =".";

        input = new SgStream(CfgFile,input.STREAM_READ);
        if (input.error != 1) {
            int num = input.readChar();
            if ( num > descriptions.length ) num = descriptions.length;
            for(int i= 0; i < num;i++)
            paths[i] = input.readPChar();
        }

        
        fileList = new javax.swing.JList();
        fileList.setSelectionMode(new javax.swing.DefaultListSelectionModel().SINGLE_SELECTION);
        jScrollPaneFiles.getViewport().setView(fileList);

        errMsg = new ErrorMessage(jLabelErrorMessage);

        selFiles();

        jTextFieldPath.setText (paths[selection]);
        
        initDone = 1;

        pack ();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the FormEditor.
     */
    private void initComponents () {//GEN-BEGIN:initComponents
        jLabelErrorMessage = new javax.swing.JLabel ();
        jTextFieldPath = new javax.swing.JTextField ();
        jButtonEdit = new javax.swing.JButton ();
        jButtonBrowsePath = new javax.swing.JButton ();
        jScrollPaneFiles = new javax.swing.JScrollPane ();
        jButtonNew = new javax.swing.JButton ();
        jComboBoxType = new javax.swing.JComboBox ();
        getContentPane ().setLayout (new org.netbeans.lib.awtextra.AbsoluteLayout ());
        addWindowListener (new java.awt.event.WindowAdapter () {
            public void windowClosing (java.awt.event.WindowEvent evt) {
                exitForm (evt);
            }
        }
        );

        jLabelErrorMessage.setBorder (new javax.swing.border.EtchedBorder(java.awt.Color.white, new java.awt.Color (134, 134, 134)));


        getContentPane ().add (jLabelErrorMessage, new org.netbeans.lib.awtextra.AbsoluteConstraints (0, 370, 530, 40));

        jTextFieldPath.setBorder (new javax.swing.border.TitledBorder(
        new javax.swing.border.EtchedBorder(java.awt.Color.white, new java.awt.Color (134, 134, 134)),
        "Path", 4, 2, new java.awt.Font ("Arial", 0, 10), java.awt.Color.black));
        jTextFieldPath.setText (".");
        jTextFieldPath.addActionListener (new java.awt.event.ActionListener () {
            public void actionPerformed (java.awt.event.ActionEvent evt) {
                jTextFieldPathActionPerformed (evt);
            }
        }
        );
        jTextFieldPath.addFocusListener (new java.awt.event.FocusAdapter () {
            public void focusLost (java.awt.event.FocusEvent evt) {
                jTextFieldPathFocusLost (evt);
            }
        }
        );


        getContentPane ().add (jTextFieldPath, new org.netbeans.lib.awtextra.AbsoluteConstraints (10, 310, 350, 50));

        jButtonEdit.setActionCommand ("Edit");
        jButtonEdit.setText ("Edit");
        jButtonEdit.addActionListener (new java.awt.event.ActionListener () {
            public void actionPerformed (java.awt.event.ActionEvent evt) {
                jButtonEditActionPerformed (evt);
            }
        }
        );


        getContentPane ().add (jButtonEdit, new org.netbeans.lib.awtextra.AbsoluteConstraints (380, 200, 130, 60));

        jButtonBrowsePath.setText ("Browse");
        jButtonBrowsePath.addActionListener (new java.awt.event.ActionListener () {
            public void actionPerformed (java.awt.event.ActionEvent evt) {
                jButtonBrowsePathActionPerformed (evt);
            }
        }
        );


        getContentPane ().add (jButtonBrowsePath, new org.netbeans.lib.awtextra.AbsoluteConstraints (380, 320, 130, 30));



        getContentPane ().add (jScrollPaneFiles, new org.netbeans.lib.awtextra.AbsoluteConstraints (10, 70, 350, 230));

        jButtonNew.setActionCommand ("New");
        jButtonNew.setText ("New");
        jButtonNew.addActionListener (new java.awt.event.ActionListener () {
            public void actionPerformed (java.awt.event.ActionEvent evt) {
                jButtonNewActionPerformed (evt);
            }
        }
        );


        getContentPane ().add (jButtonNew, new org.netbeans.lib.awtextra.AbsoluteConstraints (380, 100, 130, 60));

        jComboBoxType.addItemListener (new java.awt.event.ItemListener () {
            public void itemStateChanged (java.awt.event.ItemEvent evt) {
                jComboBoxTypeItemStateChanged (evt);
            }
        }
        );


        getContentPane ().add (jComboBoxType, new org.netbeans.lib.awtextra.AbsoluteConstraints (10, 10, 350, 50));

    }//GEN-END:initComponents

  private void jButtonNewActionPerformed (java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewActionPerformed
    // Add your handling code here:
    switch (selection) {
        case 0 : new UnitEditor (paths[selection],"new.veh",tUnit.NEW,new UnitEditor("","",0,0).DISPOSE).show ();
        default : ;
    }

  }//GEN-LAST:event_jButtonNewActionPerformed

  private void jComboBoxTypeItemStateChanged (java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxTypeItemStateChanged
    // Add your handling code here:
    if ( initDone == 1) {
        selection  = jComboBoxType.getSelectedIndex();
        jTextFieldPath.setText (paths[selection]);
        selFiles();
    }
  }//GEN-LAST:event_jComboBoxTypeItemStateChanged

  private void jTextFieldPathFocusLost (java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldPathFocusLost
    // Add your handling code here:
    pathAction();
  }//GEN-LAST:event_jTextFieldPathFocusLost

  private void jTextFieldPathActionPerformed (java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldPathActionPerformed
    // Add your handling code here:
    pathAction();
  }//GEN-LAST:event_jTextFieldPathActionPerformed

  private void jButtonEditActionPerformed (java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditActionPerformed
    // Add your handling code here:
    int sel = fileList.getSelectedIndex();
    if (sel >= 0) {
        String selName = files[sel];
        switch (selection) {
            case 0 : new UnitEditor (paths[selection],selName,tUnit.LOAD,new UnitEditor("","",0,0).DISPOSE).show ();
            default : ;
        }
    }
  }//GEN-LAST:event_jButtonEditActionPerformed

private void jButtonBrowsePathActionPerformed (java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowsePathActionPerformed
    // Add your handling code here:
    String dir;
    if ( (dir = browsePath(paths[selection])) != null ) {

        int i = dir.lastIndexOf(java.io.File.separator);
        if(i>0 && i<dir.length()-1) {
            paths[selection] =  dir.substring(0, i);

            //paths[selection] = dir;
            jTextFieldPath.setText (paths[selection]);
            selFiles();
            fileList.setSelectedValue(dir.substring(i+1), true);

        };
    }
  }//GEN-LAST:event_jButtonBrowsePathActionPerformed

/** Exit the Application */
  private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
    output = new SgStream(CfgFile,output.STREAM_WRITE);
    if (output.error != 1) {
        output.writeChar(descriptions.length);
        for(int i= 0; i < descriptions.length;i++)
        output.writePChar(paths[i]);
    }
    System.exit (0);
  }//GEN-LAST:event_exitForm

private void pathAction() {
    String path;

    path = jTextFieldPath.getText ();
    if ( checkPath(path) != 0 ) {
        jTextFieldPath.setText (paths[selection]);
        errMsg.showMessage("Invalid Path !");
    } else {
        paths[selection] = path;
        selFiles();
    }
}

private String browsePath(String startPath) {
    javax.swing.JFileChooser jFileCh;
    ExampleFileFilter filter = new ExampleFileFilter( extensions ); //extensions

    jFileCh = new javax.swing.JFileChooser(startPath);
    jFileCh.setFileFilter ( filter );
    //jFileCh.setFileSelectionMode(jFileCh.DIRECTORIES_ONLY);
    if ( jFileCh.showOpenDialog(jButtonBrowsePath) ==  jFileCh.APPROVE_OPTION ) {
        return jFileCh.getSelectedFile().getAbsolutePath();
    } else return null;
}

private void selFiles() {
    String allFiles[];
    String ext;
    java.io.File f;

    int i = 0;

    f = new java.io.File(paths[selection]);
    if ( !f.isDirectory() ) {
        paths[selection] = ".";
        f = new java.io.File(paths[selection]);
    }
        
    allFiles = f.list();

    for (int j = 0; j < allFiles.length; j ++) {
        ext = getExtension(allFiles[j]);
        if (ext != null)
        if (ext.compareTo(extensions[selection]) == 0) {
            i++;
        }
    }

    files = new String[i];

    i=0;

    for (int j = 0; j < allFiles.length; j ++) {
        ext = getExtension(allFiles[j]);
        if (ext != null)
        if (ext.compareTo(extensions[selection]) == 0) {
            files[i] = allFiles[j];
            i++;
        }
    }
    fileList.setListData(files);
}

public String getExtension(String filename) {
    int i = filename.lastIndexOf('.');
    if(i>0 && i<filename.length()-1) {
        return filename.substring(i+1).toLowerCase();
    };
    return null;
}

private int checkPath(String path) {
    java.io.File cFile = new java.io.File(path);

    if (cFile.isDirectory() == true) return 0;
    else return 1;
}

/**
 * @param args the command line arguments
 */
public static void main (String args[]) {
    new MainWindow ().show ();
}


// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabelErrorMessage;
private javax.swing.JTextField jTextFieldPath;
private javax.swing.JButton jButtonEdit;
private javax.swing.JButton jButtonBrowsePath;
private javax.swing.JScrollPane jScrollPaneFiles;
private javax.swing.JButton jButtonNew;
private javax.swing.JComboBox jComboBoxType;
// End of variables declaration//GEN-END:variables
public Unit tUnit;

static String[] descriptions = {"Vehicles","Buildings","Terrain","Technologies","Icons"};
static String[] extensions = {"veh","bld","trr","tec","nic"};
}